//
//  AlertTableView.m
//  AlertTableView
//
//  Created by 周荣水 on 16/8/2.
//  Copyright © 2016年 周荣水. All rights reserved.
//

#import "AlertTableView.h"
#import "AlertTableViewCell.h"
#import "Masonry.h"
#import "UITableView+Extension.h"
#import "KDFavorType.h"
#import "KDCollectRequestTool.h"
#define WEAK(weakSelf)  __weak __typeof(&*self)weakSelf = self;
static NSString *const reuseAlertCell = @"AlertTableViewCell";

@interface AlertTableView()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic,strong) UITableView *tableView;
/**  <#Description#> */
@property (nonatomic, copy) NSIndexPath * tempIndexPath;

/**  <#Description#> */
@property (nonatomic, strong) KDFavorType *selectType;
/**  <#Description#> */
@property (nonatomic, copy) NSString * typeName;

@end
@implementation AlertTableView

-(void)viewDidLoad{
    [super viewDidLoad];
    [self setBackGroundColor];
    [self configLayout];
}


#pragma mark BackGroundColor
- (void)setBackGroundColor
{
    self.view.backgroundColor = [UIColor clearColor];
    UIView *backGroundView = [[UIView alloc] initWithFrame:self.view.bounds];
    switch (self.viewState) {
        case viewStateNormal:
            backGroundView.backgroundColor = [UIColor clearColor];
            break;
            
        case viewStateGray:
            backGroundView.backgroundColor = [UIColor blackColor];
            backGroundView.alpha = 0.5;
            break;
            
        case viewStateWhite:
            backGroundView.backgroundColor = [UIColor whiteColor];
            backGroundView.alpha = 0.5;
            break;
        default:
            break;
    }
    
    UITapGestureRecognizer *tapToDismiss = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissSelfView)];
    [backGroundView addGestureRecognizer:tapToDismiss];
    [self.view addSubview:backGroundView];
}

- (void)dismissSelfView
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark AutoLayout
- (void)configLayout
{
    [self.view addSubview:self.tableView];
    
    switch (self.AlertcornerRaidus) {
        case IS_cornerRadiusSide:
            self.tableView.layer.cornerRadius = 7.5;
            self.tableView.layer.masksToBounds = YES;
            break;
        case IS_UncornetRaidusSide:
            
            break;
        default:
            self.tableView.layer.cornerRadius = 7.5;
            self.tableView.layer.masksToBounds = YES;
            break;
    }
    
    
    
    switch (self.AlertFromDirect) {
            
        case fromDirectCenter:
            [self alertFromCenterAType];
            break;
            
        case fromDirectBottom:
            [self alertFromBottomType];
            break;
            
        case fromDirectTop:
            [self alertFromTopType];
            self.tableView.scrollEnabled = NO;
            break;
            
        default:
            [self alertFromCenterAType];
            break;
    }
}



#pragma mark FromDirect
- (void)alertFromCenterAType
{
    WEAK(weakSelf);
    CGFloat height;
    if ([self.titleString isEqualToString:@""]) {
        height = self.rowHight * self.AlertArray.count + 1.2 *self.rowHight;;
    } else {
        height  = self.rowHight * self.AlertArray.count + 1.2 *self.rowHight*2;
    }
    
    if (height > [UIScreen mainScreen].bounds.size.height - 64- 49) {
        height = [UIScreen mainScreen].bounds.size.height - 64- 49;
    }
    [weakSelf.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(weakSelf.view);
        make.width.mas_equalTo(300);
        make.height.mas_equalTo(height);
    }];
}

- (void)alertFromBottomType
{
    WEAK(weakSelf);
    CGFloat height;
    if ([self.titleString isEqualToString:@""]) {
        height = self.rowHight * self.AlertArray.count;
    } else {
        height  = self.rowHight * self.AlertArray.count + 1.2 *self.rowHight;
    }
    
    if (height > [UIScreen mainScreen].bounds.size.height - 64- 49) {
        height = [UIScreen mainScreen].bounds.size.height - 64- 49;
    }
    [weakSelf.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leftMargin.mas_equalTo(weakSelf.view);
        make.rightMargin.mas_equalTo(weakSelf.view);
        make.bottom.mas_equalTo(weakSelf.view);
        make.height.mas_equalTo(300);
        /**
         *  项目需求，所以限制住，可以直接使用height
         */
    }];
}

- (void)alertFromTopType
{
    WEAK(weakSelf);
    CGFloat height;
    if ([self.titleString isEqualToString:@""]) {
        height = self.rowHight * self.AlertArray.count;
    } else {
        height  = self.rowHight * self.AlertArray.count + 1.2 *self.rowHight;
    }
    
    if (height > [UIScreen mainScreen].bounds.size.height - 64- 49) {
        height = [UIScreen mainScreen].bounds.size.height - 64- 49;
    }
    [weakSelf.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leftMargin.mas_equalTo(weakSelf.view);
        make.rightMargin.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo(weakSelf.view).offset(64);
        make.height.mas_equalTo(height);
    }];
}



#pragma mark TableDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.AlertArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AlertTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseAlertCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    KDFavorType *model  = [self.AlertArray objectAtIndex:indexPath.row];
    cell.titleLabel.text = model.type_name;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.rowHight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 1.2*self.rowHight)];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 1.2*self.rowHight)];
    titleLabel.backgroundColor = self.viewColor;
    titleLabel.text = self.titleString;
    [titleLabel sizeToFit];
//    titleLabel.centerX = header.centerX;
    titleLabel.center = header.center;
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [header addSubview:titleLabel];
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(CGRectGetMaxX(titleLabel.frame)+3, 0, 30, 30);
    addBtn.centerY = header.centerY;
//    [addBtn setTitle:@"全国" forState:UIControlStateNormal];
    [addBtn setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    addBtn.backgroundColor = [UIColor whiteColor];
    [addBtn setTitleColor:KDColor forState:UIControlStateNormal];;
//    self.<#btn#> = <#btn#>;
    [header addSubview:addBtn];
    return header;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ([self.titleString isEqualToString:@""]) {
        return 0;
    } else {
        return 1.2*self.rowHight;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, self.rowHight*1.2)];
    //取消按钮
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(0, 0, tableView.frame.size.width*0.5, footer.height);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(dismissSelfView) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.backgroundColor = WQColor(220, 220, 220);
//    cancelBtn.layer.cornerRadius = self.rowHight/2;
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:15.f];
    cancelBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [cancelBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [footer addSubview:cancelBtn];
    
    //确定按钮
    UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    doneBtn.frame = CGRectMake(tableView.frame.size.width*0.5, 0, tableView.frame.size.width*0.5, footer.height);
    [doneBtn setTitle:@"确定" forState:UIControlStateNormal];
    [doneBtn addTarget:self action:@selector(doneBtnClick) forControlEvents:UIControlEventTouchUpInside];
    doneBtn.backgroundColor = WQColor(220, 220, 220);
//    doneBtn.layer.cornerRadius = self.rowHight/2;
    doneBtn.titleLabel.font = [UIFont systemFontOfSize:15.f];
    doneBtn.titleLabel.textAlignment = NSTextAlignmentCenter;

    [doneBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [footer addSubview:doneBtn];
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1.2*self.rowHight;
}

#pragma mark TableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AlertTableViewCell *cell;
//    NSString *titleStr =  self.AlertArray[indexPath.row];
    if (_tempIndexPath) {
        if (_tempIndexPath != indexPath) {
            cell = [tableView cellForRowAtIndexPath:_tempIndexPath];
            cell.selectedImage.image = [UIImage imageNamed:@"icon_big_unselect"];
        }
    }
    cell = (AlertTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.selectedImage.image = [UIImage imageNamed:@"icon_big_selected"];
    
    _tempIndexPath = indexPath;
    self.selectType = self.AlertArray[indexPath.row];
//    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 事件点击区
- (void)doneBtnClick{
    self.doneBtnClickWithType(self.selectType);
}

- (void)addBtnClick:(UIButton *)addBtn{
    NSString *title = NSLocalizedString(@"新建收藏夹", nil);
    NSString *message = NSLocalizedString(@"请输入收藏夹名称", nil);
    NSString *cancelButtonTitle = NSLocalizedString(@"取消", nil);
    NSString *otherButtonTitle = NSLocalizedString(@"确定", nil);
    ;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.delegate = self;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:textField];

        //        textField.secureTextEntry = YES;
    }];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        //        NSLog(@"The \"Secure Text Entry\" alert's other action occured.");
        [self addCollectType];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:alertController.textFields.firstObject];
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        KDLog(@"The \"Secure Text Entry\" alert's cancel action occured.");
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:alertController.textFields.firstObject];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:otherAction];
    
    [self presentViewController:alertController animated:YES completion:nil];


}
#pragma mark - 网络请求区
/**
 *  添加收藏夹的请求
 */
- (void)addCollectType{
    if (!self.typeName) {
        [SVProgressHUD showErrorWithStatus:@"未输入" maskType:SVProgressHUDMaskTypeGradient];
        return;
    }
    NSDictionary *dic = @{@"type_name":self.typeName};
    WS(ws);
    [KDCollectRequestTool addFavorTypeWithParam:dic success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            KDFavorType *type = [KDFavorType objectWithKeyValues:responseObejct.data];
            NSMutableArray *arr = [NSMutableArray arrayWithArray:ws.AlertArray];
            [arr insertObject:type atIndex:0];
            ws.AlertArray = arr;
            [ws.tableView reloadData];
            //            [ws.presentedViewController dismissViewControllerAnimated:NO completion:nil];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
        [ws.presentedViewController dismissViewControllerAnimated:NO completion:nil];
        
    } failure:^(NSError *error) {
        [ws.presentedViewController dismissViewControllerAnimated:YES completion:nil];
        
        [SVProgressHUD showErrorWithStatus:@"网络问题" maskType:SVProgressHUDMaskTypeGradient];
    }];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark SET/GET

-(UITableView *)tableView{
    if (_tableView == nil) {
        UITableView *tempTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tempTableView.backgroundColor = self.viewColor;
        tempTableView.delegate = self;
        tempTableView.dataSource = self;
        [tempTableView registerNib:[UINib nibWithNibName:reuseAlertCell bundle:nil] forCellReuseIdentifier:reuseAlertCell];
        tempTableView.alwaysBounceVertical = NO;
        tempTableView.showsVerticalScrollIndicator = NO;
//        tempTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tempTableView eraseBottomSeparateLines];
        _tableView = tempTableView;
    }
    return _tableView;
}

- (NSArray *)AlertArray
{
    if (_AlertArray == nil) {
        NSArray *tempArray = [NSArray array];
        _AlertArray = tempArray;
    }
    return _AlertArray;
}

- (CGFloat)rowHight
{
    if (!_rowHight) {
        CGFloat tempHeight = 60;
        _rowHight = tempHeight;
    }
    return _rowHight;
}

- (FromDirect)AlertFromDirect
{
    if (!_AlertFromDirect) {
        FromDirect tempFromDirect = fromDirectCenter;
        _AlertFromDirect = tempFromDirect;
    }
    return _AlertFromDirect;
}

- (ViewState)viewState
{
    if (!_viewState) {
        ViewState tempviewState = viewStateNormal;
        _viewState = tempviewState;
    }
    return _viewState;
}

- (UIColor *)viewColor
{
    if (_viewColor == nil) {
        UIColor *tempColor = [UIColor whiteColor];
        _viewColor = tempColor;
    }
    return _viewColor;
}

- (NSString *)titleString
{
    if (!_titleString) {
        NSString *tempString = @"";
        _titleString = tempString;
    }
    return _titleString;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    return YES;
}
- (void)handleTextFieldTextDidChangeNotification:(NSNotification *)notification {
    UITextField *textField = notification.object;
     self.typeName = textField.text;
}


@end
